package com.liner.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liner.entity.Admin;
import com.liner.enums.ResponseEnum;
import com.liner.exception.ShopException;
import com.liner.form.AdminForm;
import com.liner.result.Result;
import com.liner.service.AdminService;
import com.liner.utils.JwtUtil;
import com.liner.utils.MD5Util;
import com.liner.vo.AdminVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liner
 * @since 2022-12-04
 */
@RestController
@RequestMapping("/admin")
@Api(tags = "管理员接口", description = "管理员登录接口")
public class AdminController {


    @Autowired
    private AdminService adminService;

    @ApiOperation("用户登录")
    @GetMapping("/login")
    public Result login(AdminForm form){
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, form.getUsername());
        Admin one = adminService.getOne(queryWrapper);
        if (one == null) {
            throw new ShopException(ResponseEnum.USERNAME_IS_NULL.getMsg());
        }

        //验证密码是否一致
        if (!MD5Util.getSaltverifyMD5(form.getPassword(),one.getPassword())) {
            throw new ShopException(ResponseEnum.PASSWORD_ERROR.getMsg());
        }

        //生成token
        String token = JwtUtil.createToken(one.getAdminId(), one.getUsername());
        AdminVo adminVo = new AdminVo();
        BeanUtils.copyProperties(one, adminVo);
        adminVo.setToken(token);

        return Result.ok(adminVo);
    }


    @ApiOperation("Token验证")
    @ApiImplicitParam(name = "token",value="token")
    @GetMapping("/checkToken")
    public Result getCheckToken(HttpServletRequest request){
        String token = request.getHeader("token");
        boolean result = JwtUtil.checkToken(token);
        if(result) return Result.ok();
        return Result.fail(ResponseEnum.TOKEN_ERROR.getMsg());
    }




}

